const { query, body, param } = require('express-validator')
const { validResultCallback } = require('../../middleware')
const { validInt, validReg, accountReg } = require('../../utils/validator')

const getAdminsValidator = [
  validInt(query, 'page'),
  validInt(query, 'limit'),
  validReg(query, 'status', /^[01]$/),
  validResultCallback
]

const createAdminValidator = [
  body('account')
    .exists({ checkFalsy: true })
    .withMessage('account 未传')
    .bail()
    .custom(value => accountReg.test(value))
    .withMessage('account 格式错误(英文+数字)'),
  body('pwd')
    .exists({ checkFalsy: true })
    .withMessage('pwd 未传'),
  body('pwdConfirm')
    .exists({ checkFalsy: true })
    .withMessage('pwdConfirm 未传')
    .bail()
    .custom((value, { req }) => value === req.body.pwd)
    .withMessage('两个密码不一样'),
  body('roles', 'roles 格式错误')
    .isArray()
    .bail()
    .custom(arr => !arr.some(v => typeof v !== 'number' || /[^\d]/.test(v))),
  body('status')
    .exists()
    .withMessage('status 未传')
    .bail()
    .custom(value => [0, 1].includes(value))
    .withMessage('status 格式错误'),
  body('realName')
    .exists({ checkFalsy: true })
    .withMessage('realName 未传'),
  validResultCallback
]

const updateAdminValidator = [
  body('roles', 'roles 格式错误')
    .isArray()
    .bail()
    .custom(arr => !arr.some(v => typeof v !== 'number' || /[^\d]/.test(v))),
  body('status')
    .if(body('status').exists())
    .custom(value => [0, 1].includes(value))
    .withMessage('status 格式错误'),
  body('realName')
    .exists({ checkFalsy: true })
    .withMessage('realName 未传'),
  validResultCallback
]

const statusValidator = [
  param('status')
    .exists()
    .withMessage('status 未传')
    .bail()
    .custom(value => ['0', '1'].includes(value))
    .withMessage('status 格式错误'),
  validResultCallback
]

const pwdValidator = [
  body('pwd')
    .exists({ checkFalsy: true })
    .withMessage('pwd 未传'),
  body('pwdConfirm')
    .exists({ checkFalsy: true })
    .withMessage('pwdConfirm 未传')
    .bail()
    .custom((value, { req }) => value === req.body.pwd)
    .withMessage('两个密码不一样'),
  validResultCallback
]

module.exports = {
  getAdminsValidator,
  createAdminValidator,
  updateAdminValidator,
  statusValidator,
  pwdValidator
}
